package com.springsource.a10SpringAOP;

import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

public class A101 {

    public static void main(String[] args) {
        // 准备切点 pointcut
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* sayHello())");
        // 通知 advice
        MethodInterceptor methodInterceptor = invocation -> {
            System.out.println("before");
            Object result = invocation.proceed();
            System.out.println("after");
            return result;
        };
        // 织入
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, methodInterceptor);
        // 代理
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(new Target1());
        proxyFactory.addAdvisor(advisor);
        proxyFactory.setInterfaces(Target1.class.getInterfaces());
        I1 proxy = (I1) proxyFactory.getProxy();
        proxy.sayHello();
    }

    public interface I1 {
        void sayHello();
        void sayGoodbye();
    }

    public static class Target1 implements I1 {
        public void sayHello() {
            System.out.println("Target1 Hello");
        }
        public void sayGoodbye() {
            System.out.println("Target1 Goodbye");
        }
    }

    public static class Target2 {
        public void sayHello() {
            System.out.println("Target2 Hello");
        }
        public void sayGoodbye() {
            System.out.println("Target2 Goodbye");
        }
    }


}
